<script setup lang="ts">
import {spriteMapLocation} from "@/assets/js/spriteMapLocation";
import {onMounted, reactive, ref, watch} from "vue";
import {settings} from "@/settings";
const props = defineProps({
  name: {
    type: String,
    required: true
  }
})
const positionIndex = ref(0)
let data = spriteMapLocation[props.name]
const spriteBac = reactive({
  x: '0px',
  y: '0px',
  src: ``
})
const spriteImage = reactive({
  x: '0px',
  y: '0px',
  src: ``
})


const init = ()=>{
  positionIndex.value = 0
  data = spriteMapLocation[props.name]
  const bacData = data.bac && data.bac !== 'none' ? spriteMapLocation[data.bac] : data
  spriteBac.x = bacData.animates[positionIndex.value].x + 'px'
  spriteBac.y = bacData.animates[positionIndex.value].y + 'px'
  spriteBac.src = `url(${data.bac === 'none' ? '' : bacData.src})`

  if(data.bac){
    spriteImage.x = data.animates[0].x + 'px'
    spriteImage.y = data.animates[0].y + 'px'
    spriteImage.src = `url(${data.src})`
  }

  if(data.autoplay){
    const addAnimate = ()=>{
      setTimeout(()=>{
        positionIndex.value++
        if(positionIndex.value > data.animates.length - 1){
          positionIndex.value = 0
        }
        addAnimate()
      },settings.animationIntervalTime)
    }
    addAnimate()
  }
}
watch(()=>positionIndex.value,()=>{
  if(positionIndex.value <= data.animates.length - 1 && positionIndex.value>=0){
    spriteImage.x = data.animates[positionIndex.value].x + 'px'
    spriteImage.y = data.animates[positionIndex.value].y + 'px'
  }
})
watch(() => props.name,init)
init()
const movePerson = ()=>{
  if(positionIndex.value < data.animates.length - 1){
    positionIndex.value++
  }else{
    positionIndex.value = 0
  }
  return positionIndex.value
}
defineExpose({movePerson:movePerson})
</script>

<template>
<div class="sprite-background">
  <span v-if="spriteImage.src" class="spriteImage"></span>
</div>
</template>

<style scoped>
.sprite-background{
  background: v-bind('spriteBac.src') no-repeat v-bind('spriteBac.x') v-bind('spriteBac.y');
  width: calc(v-bind('settings.width') * 1px);
  height: calc(v-bind('settings.height') * 1px);
  display: inline-block;
}
.spriteImage{
  background: v-bind('spriteImage.src') no-repeat v-bind('spriteImage.x') v-bind('spriteImage.y');
  width: calc(v-bind('settings.width') * 1px);
  height: calc(v-bind('settings.height') * 1px);
  display: inline-block;
}
</style>
